//
//  H5Downloader.m
//  dsBridge
//
//  Created by sxh on 2020/9/21.
//

#import "SXHDownloader.h"
#import "SSZipArchive.h"
#import "SXHFileManager.h"
#import "NSObject+UIViewController.h"
#import "SXHWebViewController.h"
#import "macro.h"

@interface SXHDownloader()
<
    NSURLSessionDownloadDelegate
>

//下载task
@property (nonatomic , strong) NSURLSessionDownloadTask *downloadTask;
//文件下载地址
@property (nonatomic , strong) NSString *downloadPath;
///模块化参数
@property (nonatomic, strong) NSString *agreement;
@property (nonatomic, strong) NSString *appid;
//当前本地web资源的版本号
@property (nonatomic, strong) NSString *webVersion;

@property (nonatomic, strong) DownloadResultBlock downloadBlock;

@end

@implementation SXHDownloader

+ (instancetype)sharedInstace {
    static SXHDownloader *shared = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        shared = [[SXHDownloader alloc] init];
    });
    return shared;
}

- (void)requestFileUrl:(NSString *)urlStr
            webVersion:(NSString *)webVersion
              complete:(DownloadResultBlock)complete {
    NSLog(@"%@",self.zlzk_viewController);
    _webVersion = webVersion;
    _downloadBlock = complete;
    if ([self.zlzk_viewController isKindOfClass:[SXHWebViewController class]]) {
        SXHWebViewController *webview = (SXHWebViewController *)self.zlzk_viewController;
        _downloadPath = kDownloadDirectory(webview.agreement, webview.appid);
        _agreement = webview.agreement;
        _appid = webview.appid;
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
        NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
        NSURLSession *sesstion = [NSURLSession sessionWithConfiguration:sessionConfiguration delegate:self delegateQueue:[NSOperationQueue mainQueue]];
        NSURLSessionDownloadTask *downloadTask = [sesstion downloadTaskWithRequest:request];
        self.downloadTask = downloadTask;
        [downloadTask resume];
    }
}

#pragma mark NSURLSessionDownloadDelegate
/**
 *  写数据
 *
 *  @param session                   会话对象
 *  @param downloadTask              下载任务
 *  @param bytesWritten              本次写入的数据大小
 *  @param totalBytesWritten         下载的数据总大小
 *  @param totalBytesExpectedToWrite  文件的总大小
 */
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
    //1. 获得文件的下载进度
//    NSLog(@"%f",1.0 * totalBytesWritten/totalBytesExpectedToWrite);
    _downloadBlock(DownLoadStatusIng, 1.0 * totalBytesWritten/totalBytesExpectedToWrite, _downloadPath, nil);
}

/**
*  当下载完成的时候调用
*
*  @param location     文件的临时存储路径
*/
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
    NSLog(@"%@",location);
    WS(weakSelf)
    //1 拼接文件全路径
//    NSString *fullPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
    NSString *fullPath = [NSString stringWithFormat:@"%@/%@",_downloadPath,downloadTask.response.suggestedFilename];
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:fullPath]) {
        [[NSFileManager defaultManager] removeItemAtPath:fullPath error:nil];
    }
    //2 必须要剪切文件, 因为系统默认会删除
    [[NSFileManager defaultManager] moveItemAtURL:location toURL:[NSURL fileURLWithPath:fullPath] error:nil];
    
    //备份
//    [[SXHFileManager sharedInstace] copyDirectoryToWorkPath:_agreement withAppid:_appid isForce:NO];
    
    NSString *targetPath = kWidgetDirectory(_agreement, _appid);
    
    //解压文件
    [SSZipArchive unzipFileAtPath:fullPath toDestination:targetPath overwrite:YES password:nil progressHandler:nil completionHandler:^(NSString * _Nonnull path, BOOL succeeded, NSError * _Nullable error) {

        if (succeeded) {
            //解压成功=更新成功 -> 设置当前版本号
            NSString *webVersionKey = [NSString stringWithFormat:@"%@+%@+%@", weakSelf.agreement, weakSelf.appid, AppVersion];
            kSetValueForKey(weakSelf.webVersion, webVersionKey);
    
            weakSelf.downloadBlock(UnZipStatusSuccess, 1.000, fullPath, kWidgetDirectory(weakSelf.agreement, weakSelf.appid));
        }else {
            NSLog(@"解压错误:%@",error.userInfo);
            weakSelf.downloadBlock(UnZipStatusFailed, 1.000, fullPath, nil);
        }
    }];
}

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
    if (error) {
        
        _downloadBlock(DownLoadStatusFailed, 0, nil, nil);
    }
}

@end
